package org.nokatag.system;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;

import org.springframework.core.io.Resource;

/**
 * 初始资源文件
 * <p>@Title </p>
 * <p>@Description </p>
 * <p>@Version 1.0.0</p>
 * <p>@author fangjianxie</p>
 * <p>@date 2018年5月22日</p>
 * <p>xiefangjian@163.com</p>
 * <p>Copyright © Noka Laboratory.All Rights Reserved.</p>
 */
public class ResourcesThread extends Thread{
    private Resource[] mapperLocations;

    public ResourcesThread(Resource[] mapperLocations){
        this.mapperLocations = mapperLocations;
    }

    public void run() {
        try {
            for (Resource mapperLocation : mapperLocations) {
                try {
                    String resourcePath = mapperLocation.getURL().toString();
                    resourcePath = resourcePath.substring(resourcePath.indexOf("/classes/") + "/classes/".length());
                    if (Concest.FILE_CACHE.get(resourcePath) == null) {
                        InputStream fi = mapperLocation.getInputStream();
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        try {
                            final byte[] buffer = new byte[4096];
                            int n;
                            while (-1 != (n = fi.read(buffer))) {
                                out.write(buffer, 0, n);
                            }
                            out.close();
                            fi.close();
                            Concest.FILE_CACHE.put(resourcePath, out.toByteArray());
                            Concest.FILE_LAST_UPDATE_TIME.put(resourcePath, new Date().getTime());
                        } catch (Exception ex) {
                        } finally {
                            if (null != fi) {
                                fi.close();
                            }
                            if (null != out) {
                                out.close();
                            }
                        }
                    }
                } catch (Exception es) {

                }
            }
        } catch (Exception se) {
            se.printStackTrace();
        }
    }
}